/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/**
 * \file
 * \brief MaCI Logger Main Frame and filename dialog implementations.
 * \author Matthieu Myrsky <matthieu.myrsky@tkk.fi>
 * \author wxFormBuilder (Autogenerated base code)
 *
 * $Id: MaCI_Logger_MainFrame.cpp,v 1.25 2009-06-29 11:32:48 morsko Exp $
 *
 */
#include "MaCI_Logger_MainFrame.h"
#include "MaCI_Logger_About_Dialog.h"
DEFINE_EVENT_TYPE(MY_EVENT_UPDATESERVICELIST);
DEFINE_EVENT_TYPE(MY_EVENT_ADDITIONALINFOUPDATE);
BEGIN_EVENT_TABLE(MaCI_Logger_MainFrame, wxFrame)
  EVT_COMMAND(wxID_ANY, MY_EVENT_UPDATESERVICELIST, MaCI_Logger_MainFrame::UpdateServiceList)
  EVT_TIMER(MY_EVENT_ADDITIONALINFOUPDATE, MaCI_Logger_MainFrame::OnAdditionalInfoUpdate)
END_EVENT_TABLE();

MaCI_Logger_MainFrame::MaCI_Logger_MainFrame( wxWindow* parent )
:
  MainFrame( parent ),
  iGIMIPtr(NULL),
  iServiceList(),
  iNewServiceList(),
  iVersionNumber("1.8.1"),
  iAdditionalInformationTimer()
{


  m_listCtrl_Services->InsertColumn(0,wxT("Services"));
  m_listCtrl_Services->SetColumnWidth(0, 400);
  m_listCtrl_Services->InsertColumn(1,wxT("Additional Information"));
  m_listCtrl_Services->SetColumnWidth(1, 600);
  m_menubar1->EnableTop(1,false);

  // Setup timer.
  iAdditionalInformationTimer.SetOwner(this, MY_EVENT_ADDITIONALINFOUPDATE);
  iAdditionalInformationTimer.Start(100);
}
//*****************************************************************************

MaCI_Logger_MainFrame::~MaCI_Logger_MainFrame()
{
 
  /* if(iMenuAddedToBar){
    int size = m_menubar1->GetMenuCount();
    m_menubar1->Remove(size-1);
    iMenuAddedToBar = false;
    }*/
  //Stop timer
  iAdditionalInformationTimer.Stop();
  //Remove logger items from menubar
 




 
  for(int i = 0; i <m_listCtrl_Services->GetItemCount();i++){
    Logger *log = reinterpret_cast<Logger *>(m_listCtrl_Services->GetItemData(i));

    log->StopLogging();

    
    if(m_listCtrl_Services->GetItemState(i,wxLIST_STATE_SELECTED)){
      if(iMenuMap[log]){
        wxMenu* menu = m_menubar1->Remove(2);
      }
    }
    
    delete log;
  }    
  m_listCtrl_Services->DeleteAllItems();
  
}
//*****************************************************************************

void MaCI_Logger_MainFrame::OnButtonStartClick( wxCommandEvent& event )
{
	// TODO: Implement OnButtonStartClick
  int state;
  UpdateLoggerMenus();
  for(unsigned int i = 0; i <m_listCtrl_Services->GetItemCount();i++){
    Logger *log = reinterpret_cast<Logger *>(m_listCtrl_Services->GetItemData(i));
    state = m_listCtrl_Services->GetItemState(i,wxLIST_STATE_SELECTED);

    if(state != 0){
      log->StartLogging();
      wxColour green(0,255,0);
      m_listCtrl_Services->SetItemTextColour(i,green);
     
    }


  }
}
//*****************************************************************************
void MaCI_Logger_MainFrame::OnStartAllClick( wxCommandEvent& event )
{
  int state;
  UpdateLoggerMenus();
  for(unsigned int i = 0; i <m_listCtrl_Services->GetItemCount();i++){
    Logger *log = reinterpret_cast<Logger *>(m_listCtrl_Services->GetItemData(i));
   
    log->StartLogging();
    wxColour green(0,255,0);
    m_listCtrl_Services->SetItemTextColour(i,green);


  }

}
//*****************************************************************************

void MaCI_Logger_MainFrame::OnButtonStopClick( wxCommandEvent& event )
{
  int state;

  for(unsigned int i = 0; i <m_listCtrl_Services->GetItemCount();i++){
    Logger *log = reinterpret_cast<Logger *>(m_listCtrl_Services->GetItemData(i));
    state = m_listCtrl_Services->GetItemState(i,wxLIST_STATE_SELECTED);
    if(state != 0){
      log->StopLogging();
      wxColour red(255,0,0);
      m_listCtrl_Services->SetItemTextColour(i,red);
    }


  }

}
//*****************************************************************************

void MaCI_Logger_MainFrame::OnStopAllClick( wxCommandEvent& event )
{

  for(unsigned int i = 0; i <m_listCtrl_Services->GetItemCount();i++){
    Logger *log = reinterpret_cast<Logger *>(m_listCtrl_Services->GetItemData(i));
      
    log->StopLogging();
    wxColour red(255,0,0);
    m_listCtrl_Services->SetItemTextColour(i,red);
    
  }
}
//*****************************************************************************

void MaCI_Logger_MainFrame::OnSelectedServicesDClick( wxCommandEvent& event )
{
	// TODO: Implement OnSelectedServicesDClick
}
//*****************************************************************************

void MaCI_Logger_MainFrame::OnListSelected(wxListEvent& event)
{
  int item = event.GetIndex();
  dPrint(10,"item %d",item);
  
  if(item >=0 && item < m_listCtrl_Services->GetItemCount()){
    m_menubar1->EnableTop(1,true);


    Logger *logger = reinterpret_cast<Logger *>(m_listCtrl_Services->GetItemData(item));
    if(logger){
      
      wxMenu *menu = iMenuMap[logger];
    
      if(menu){
        int placeToAdd = 0;
        //Go through all selected services before this event item
        for(int i = 0; i< item; i++){
          if(m_listCtrl_Services->GetItemState(i,wxLIST_STATE_SELECTED)){
            Logger *log = reinterpret_cast<Logger *>(m_listCtrl_Services->GetItemData(i));
            //if the previous services have menu add item menu after this one
            if(iMenuMap[log]){
              placeToAdd++;
            }

          }

        }
        menu->Insert(0,99,m_listCtrl_Services->GetItemText(item));

        // dPrint(1,"Inserting at %d", 2+placeToAdd);
        
        m_menubar1->Insert(2+placeToAdd,menu,"Log types");
       
      }
      
    }

 
  }
}
//*****************************************************************************

void MaCI_Logger_MainFrame::OnMenuSetFilenameSelected( wxCommandEvent& event )
{
  int state;

  for(unsigned int i = 0; i <m_listCtrl_Services->GetItemCount();i++){
    Logger *log = reinterpret_cast<Logger *>(m_listCtrl_Services->GetItemData(i));
    state = m_listCtrl_Services->GetItemState(i,wxLIST_STATE_SELECTED);
    
    if(state != 0){
      MaCI_Logger_Filename_Dialog dia(this,
                                      log,
                                      std::string(m_listCtrl_Services->GetItemText(i).mb_str()));
      dia.ShowModal();
    }


  }


}
//*****************************************************************************

void MaCI_Logger_MainFrame::OnListDeselected(wxListEvent& event)
{

  int index = event.GetIndex();
  Logger *logger = reinterpret_cast<Logger *>(m_listCtrl_Services->GetItemData(index));
  if(logger){
    
    wxMenu *menu = iMenuMap[logger];
    if(menu){
      
      int placeToRemove = 0;
      for(int i = 0; i< index; i++){
        if(m_listCtrl_Services->GetItemState(i,wxLIST_STATE_SELECTED)){
          Logger *log = reinterpret_cast<Logger *>(m_listCtrl_Services->GetItemData(i));
          //if the previous services have menu add item menu after this one
          if(iMenuMap[log]){
            placeToRemove++;
          }

        }
      }
      int size = m_menubar1->GetMenuCount();
      //dPrint(1,"Removing %d", 2+placeToRemove);
      wxMenu* menu = m_menubar1->Remove(2+placeToRemove);
      menu->Remove(99);
      if(m_listCtrl_Services->GetSelectedItemCount() ==0){
        m_menubar1->EnableTop(1,false); 
      }
    }
    
  }

  
}
//*****************************************************************************

void MaCI_Logger_MainFrame::OnListRightClick(wxListEvent& event)
{
 
  int item = event.GetIndex();
  wxPoint position = event.GetPoint();

  //Get menu from logger
  if(item >=0 && item < m_listCtrl_Services->GetItemCount()){
    Logger *logger = reinterpret_cast<Logger *>(m_listCtrl_Services->GetItemData(item));
    
    wxMenu *menu = iMenuMap[logger];
    
    //if menu found add a separator, 'SET' line and SetFilename menuitem
    if(menu){
      int size = menu->GetMenuItemCount();
      wxMenuItem *sep = menu->InsertSeparator(size);
      wxMenuItem *item = menu->Insert(size+1,size+1,"SET");
     
      menu->Insert(size+2,m_menu_Set->FindItem(wxID_SetFilename));
      menu->Insert(size+3,m_menu_Set->FindItem(wxID_Start));
      menu->Insert(size+4,m_menu_Set->FindItem(wxID_Stop));      
      if(logger->SupportMeasurementSkipping()){
        menu->Insert(size+5,m_menu_Set->FindItem(wxID_Skip));
        
      }
      PopupMenu(menu,position.x,position.y);
      menu->Destroy(sep);
      menu->Destroy(item);
      menu->Remove(m_menu_Set->FindItem(wxID_SetFilename));
      menu->Remove(m_menu_Set->FindItem(wxID_Start));
      menu->Remove(m_menu_Set->FindItem(wxID_Stop));
      if(logger->SupportMeasurementSkipping()){
        menu->Remove(m_menu_Set->FindItem(wxID_Skip));
      }

     

    }else{
      //if menu not found from logger add 'Set' line and SetFilename menuitem
      menu = new wxMenu();
      wxMenuItem *item =  menu->Insert(0,0,"SET");
      menu->Insert(1,m_menu_Set->FindItem(wxID_SetFilename));
      menu->Insert(2,m_menu_Set->FindItem(wxID_Start));
      menu->Insert(3,m_menu_Set->FindItem(wxID_Stop));
      if(logger->SupportMeasurementSkipping()){
        menu->Insert(4,m_menu_Set->FindItem(wxID_Skip));
      }
      PopupMenu(menu,position.x,position.y);
      menu->Remove(m_menu_Set->FindItem(wxID_SetFilename));
      menu->Remove(m_menu_Set->FindItem(wxID_Start));
      menu->Remove(m_menu_Set->FindItem(wxID_Stop));
      if(logger->SupportMeasurementSkipping()){
        menu->Remove(m_menu_Set->FindItem(wxID_Skip));
      }
      delete(menu);


    }
    
  }

}
//*****************************************************************************

bool MaCI_Logger_MainFrame::Initialize(gimi::GIMI *aGimiPtr, int aGimboID, int aReportID)
{
  bool result = true;
  
  // Store for future reference.
  iGIMIPtr = aGimiPtr;
  
  iLoggerGenerator = new LoggerGenerator(iGIMIPtr);
  // Start the Gimbo core.
  CComponent::Start(aGimiPtr, aGimboID, aReportID);

  iMaCICtrlClient =new MaCI::MaCICtrl::CMaCICtrlClient(aGimiPtr);
  
  if (iMaCICtrlClient->Open()!=MaCI::KMaCIOK){
    
    dPrint(1,"Couldn't open MaCICtrl client");
    result = false;
  }
  
  return result;
}
//*****************************************************************************

void MaCI_Logger_MainFrame::OnServiceAssignment(const Gimbo::TServiceAssignmentList &aServiceList)
{
  dPrint(ODSTATUS,"Event: OnServiceAssignment");
  
  iNewServiceList = aServiceList;
   
  //Update servicelist
  wxCommandEvent e( MY_EVENT_UPDATESERVICELIST, GetId() );
  AddPendingEvent(e);
}
//*****************************************************************************

void MaCI_Logger_MainFrame::UpdateServiceList(wxCommandEvent &aEvent){

  Gimbo::TServiceAssignmentList::const_iterator si;
  wxArrayString stringarray;


  gimi::t_serviceList gimiServices;
  iMaCICtrlClient->DiscoverMaCICtrlServices(gimiServices,5000); 
  MaCI::MaCICtrl::TServiceEntryArray entries;
  MaCI::MaCICtrl::TServiceEntryArray::iterator iter;
  iMaCICtrlClient->GetServiceArray(entries, gimiServices);

  for (si=iNewServiceList.begin(); si!=iNewServiceList.end(); si++){
    bool alreadyAtList = false;
    for(int i = 0; i< iServiceList.size();i++){
      
      if(iServiceList[i]== *si){
        alreadyAtList = true;
        break;
      }
    }
    if(!alreadyAtList){
      iServiceList.push_back(*si);
      std::string name;
      GetGimi()->findClientName(name,si->targetID,5000);
      MaCI::MaCICtrl::SMaCISL maciSL;
      

      
      if(iMaCICtrlClient->FindMaCISL(maciSL,
                                     entries,
                                     name,
                                     si->majorType,
                                     si->minorType) == MaCI::KMaCIOK){
        name = maciSL.ToMaCISLString();
        dPrint(6,"MaCISL name is '%s'",name.c_str());
      }
      Logger *logger = iLoggerGenerator->GenerateNewLogger(si->majorType, si->minorType, si->targetID,name);

      if(logger !=NULL){
        int numberOfItems = m_listCtrl_Services->GetItemCount();
        int index = m_listCtrl_Services->InsertItem(numberOfItems,name);

        m_listCtrl_Services->SetItemPtrData(index,(wxUIntPtr)logger);        
        Logger::TMenu *menu = logger->GetMenu();
        wxMenu *wxm = NULL;
        if(menu){
          wxm = new wxMenu();
        
          wxMenuItem *mItem = new wxMenuItem(NULL,0,"Log types");

          int index = 0;
          for(Logger::TMenu::iterator i = menu->begin(); i !=menu->end(); i++){
           
            wxMenuItem *it = wxm->InsertCheckItem(index,index,i->first);
           
            it->Check(i->second);
            index++;
            
          }
        }

        iMenuMap[logger] = wxm;
    
        //iMenuMap[logger] = menu;
        wxColour red(255,0,0);
        m_listCtrl_Services->SetItemTextColour(index,red);
      }
    }
  }
  dPrint(3,"Finished to update servicelist ");
}
/*
  void MaCI_Logger_MainFrame::UpdateServiceList(wxCommandEvent &aEvent){
  Gimbo::TServiceAssignmentList::const_iterator si;
  wxArrayString stringarray;


  gimi::t_serviceList gimiServices;
  iMaCICtrlClient->DiscoverMaCICtrlServices(gimiServices,5000); 
  MaCI::MaCICtrl::TServiceEntryArray entries;
  MaCI::MaCICtrl::TServiceEntryArray::iterator iter;
  iMaCICtrlClient->GetServiceArray(entries, gimiServices);


  for (si=iNewServiceList.begin(); si!=iNewServiceList.end(); si++){
    bool alreadyAtList = false;
    for(int i = 0; i< iServiceList.size();i++){

      if(iServiceList[i]== *si){
        alreadyAtList = true;
        break;
      }
    }
    if(!alreadyAtList){
      iServiceList.push_back(*si);
      
      
      ///*search maci name
      std::string name;
      GetGimi()->findClientName(name,si->targetID,5000);
      MaCI::MaCICtrl::SMaCISL maciSL;
      

      
      if(iMaCICtrlClient->FindMaCISL(maciSL,
                                     entries,
                                     name,
                                     si->majorType,
                                     si->minorType) == MaCI::KMaCIOK){
        name = maciSL.ToMaCISLString();
        dPrint(6,"MaCISL name is '%s'",name.c_str());
      }
    
      ///***************************************************************
      ///***************************************************************
      ///***************************************************************
      ///***********CONSTRUCT LOGGER************************************
      ///***************************************************************
      ///***************************************************************
      ///***************************************************************
      if(si->majorType== GIMI_PROTOCOL_MACI_RANGING){
        ///////////////////////////////////////////////////////////////
        ////////// Ranging
        ///////////////////////////////////////////////////////////////
        dPrint(6,"Constructing ranging");
        MaCI::Ranging::CRangingClient *rangingClient = new MaCI::Ranging::CRangingClient(iGIMIPtr,si->minorType);
        rangingClient->SetDefaultTarget(si->targetID);
        
        if (rangingClient->Open()==MaCI::KMaCIOK){
          dPrint(3,"Ranging opened");
          RangingLogger *rlogger= new RangingLogger(rangingClient,name);
          
          rlogger->SetService(*si);
          
          int numberOfItems = m_listCtrl_Services->GetItemCount();
          int index = m_listCtrl_Services->InsertItem(numberOfItems,name);
          
          m_listCtrl_Services->SetItemPtrData(index,(wxUIntPtr)(static_cast<Logger *>(rlogger)));        
          
          
          wxColour red(255,0,0);
          m_listCtrl_Services->SetItemTextColour(index,red);
          
          
        } else {
          std::string s = "Could not open Ranging client";
          dPrint(1,"%s",s.c_str());
          delete rangingClient;
        }
        
      }else if(si->majorType== GIMI_PROTOCOL_MACI_POSITION){
        ///////////////////////////////////////////////////////////////
        ////////// Position
        ///////////////////////////////////////////////////////////////
        dPrint(6,"Constructing position");
        MaCI::Position::CPositionClient *positionClient = new MaCI::Position::CPositionClient(iGIMIPtr,si->minorType);
        positionClient->SetDefaultTarget(si->targetID);
        if (positionClient->Open()==MaCI::KMaCIOK){
          
          PositionLogger *plogger= new PositionLogger(positionClient,name);
          
          plogger->SetService(*si);
          
          int numberOfItems = m_listCtrl_Services->GetItemCount();
          int index = m_listCtrl_Services->InsertItem(numberOfItems,name);
          
          m_listCtrl_Services->SetItemPtrData(index,(wxUIntPtr)(static_cast<Logger *>(plogger)));        
          
          
          wxColour red(255,0,0);
          m_listCtrl_Services->SetItemTextColour(index,red);
          
          
        } else {
          std::string s = "Could not open Position client";
          
          dPrint(1,"%s",s.c_str());
          delete positionClient;
        }
      }else if(si->majorType== GIMI_PROTOCOL_MACI_SPEEDCTRL){
        ///////////////////////////////////////////////////////////////
        ////////// SpeedCTRL
        ///////////////////////////////////////////////////////////////
        dPrint(6,"Constructing speedctrl");
        MaCI::SpeedCtrl::CSpeedCtrlClient *speedCtrlClient = new MaCI::SpeedCtrl::CSpeedCtrlClient(iGIMIPtr,si->minorType);
        speedCtrlClient->SetDefaultTarget(si->targetID);
        if (speedCtrlClient->Open()==MaCI::KMaCIOK){
          
          SpeedCtrlLogger *slogger= new SpeedCtrlLogger(speedCtrlClient,name);
          
          slogger->SetService(*si);
          
          int numberOfItems = m_listCtrl_Services->GetItemCount();
          int index = m_listCtrl_Services->InsertItem(numberOfItems,name);
          
          m_listCtrl_Services->SetItemPtrData(index,(wxUIntPtr)(static_cast<Logger *>(slogger)));        
          
          
          wxColour red(255,0,0);
          m_listCtrl_Services->SetItemTextColour(index,red);
          
          
        } else {
          std::string s = "Could not open SpeedCtrl client";
          dPrint(1,"%s",s.c_str());

          delete speedCtrlClient;
        }
        
      }else if(si->majorType== GIMI_PROTOCOL_MACI_IMU){
        ///////////////////////////////////////////////////////////////
        ////////// IMU
        ///////////////////////////////////////////////////////////////        
        dPrint(6,"Constructing IMU");
        MaCI::IMU::CIMUClient *imuClient = new MaCI::IMU::CIMUClient(iGIMIPtr,si->minorType);
        imuClient->SetDefaultTarget(si->targetID);
        if (imuClient->Open()==MaCI::KMaCIOK){
          
          IMULogger *ilogger= new IMULogger(imuClient,name);
          
          ilogger->SetService(*si);
          
          int numberOfItems = m_listCtrl_Services->GetItemCount();
          int index = m_listCtrl_Services->InsertItem(numberOfItems,name);
          
          m_listCtrl_Services->SetItemPtrData(index,(wxUIntPtr)(static_cast<Logger *>(ilogger)));        
          
          
          wxColour red(255,0,0);
          m_listCtrl_Services->SetItemTextColour(index,red);
          
          
        } else {
          std::string s = "Could not open IMU client";
          dPrint(1,"%s",s.c_str());

          delete imuClient;
        }
        
      }else if(si->majorType == GIMI_PROTOCOL_MACI_ENERGY){
        ///////////////////////////////////////////////////////////////
        ////////// Energy
        ///////////////////////////////////////////////////////////////
        dPrint(6,"Constructing IMU");
        MaCI::Energy::CEnergyClient *energyClient = new MaCI::Energy::CEnergyClient(iGIMIPtr,si->minorType);
        energyClient->SetDefaultTarget(si->targetID);
        if (energyClient->Open()==MaCI::KMaCIOK){
          
          EnergyLogger *elogger= new EnergyLogger(energyClient,name);
          
          elogger->SetService(*si);
          
          int numberOfItems = m_listCtrl_Services->GetItemCount();
          int index = m_listCtrl_Services->InsertItem(numberOfItems,name);
          
          m_listCtrl_Services->SetItemPtrData(index,(wxUIntPtr)(static_cast<Logger *>(elogger)));        
          
          
          wxColour red(255,0,0);
          m_listCtrl_Services->SetItemTextColour(index,red);
          
          
        } else {
          std::string s = "Could not open energy client";
          dPrint(1,"%s",s.c_str());

          delete energyClient;
        }
      }else if(si->majorType == GIMI_PROTOCOL_MACI_WIRELESS){
        ///////////////////////////////////////////////////////////////
        ////////// Wireless
        ///////////////////////////////////////////////////////////////
        dPrint(6,"Constructing Wireless");
        MaCI::Wireless::CWirelessClient *wirelessClient = new MaCI::Wireless::CWirelessClient(iGIMIPtr, si->minorType);
        wirelessClient->SetDefaultTarget(si->targetID);
        
        if (wirelessClient->Open() == MaCI::KMaCIOK) {
          WirelessLogger *wlogger= new WirelessLogger(wirelessClient,name);
          wlogger->SetService(*si);
          
          const int numberOfItems = m_listCtrl_Services->GetItemCount();
          const int index = m_listCtrl_Services->InsertItem(numberOfItems, name);
          
          // Add itemdata. (Don't know why, but others do it too :)
          m_listCtrl_Services->SetItemPtrData(index,(wxUIntPtr)(static_cast<Logger *>(wlogger)));        
          
          wxColour red(255,0,0);
          m_listCtrl_Services->SetItemTextColour(index,red);
          
        } else {
          std::string s = "Could not open wireless client";
          dPrint(1,"%s",s.c_str());

          delete wirelessClient;
        } 
       
      }else if(si->majorType == GIMI_PROTOCOL_MACI_COORDINATEDRIVE){
        ///////////////////////////////////////////////////////////////
        ////////// CoordinateDrive
        ///////////////////////////////////////////////////////////////
        dPrint(6,"Constructing CoordinateDrive");
        MaCI::CoordinateDrive::CCoordinateDriveClient *coordinateDriveClient = new MaCI::CoordinateDrive::CCoordinateDriveClient(iGIMIPtr, si->minorType);
        coordinateDriveClient->SetDefaultTarget(si->targetID);
        
        if (coordinateDriveClient->Open() == MaCI::KMaCIOK) {
          CoordinateDriveLogger *clogger= new CoordinateDriveLogger(coordinateDriveClient,name);
          clogger->SetService(*si);
          
          const int numberOfItems = m_listCtrl_Services->GetItemCount();
          const int index = m_listCtrl_Services->InsertItem(numberOfItems, name);
          

          m_listCtrl_Services->SetItemPtrData(index,(wxUIntPtr)(static_cast<Logger *>(clogger)));        
          
          wxColour red(255,0,0);
          m_listCtrl_Services->SetItemTextColour(index,red);
          
        } else {
          std::string s = "Could not open CoordinateDrive client";
          dPrint(1,"%s",s.c_str());

          delete coordinateDriveClient;
        } 
      }else if(si->majorType == GIMI_PROTOCOL_MACI_IMAGE){
        ///////////////////////////////////////////////////////////////
        ////////// Image
        ///////////////////////////////////////////////////////////////
        dPrint(6,"Constructing Image client");
        MaCI::Image::CImageClient *imageClient = new MaCI::Image::CImageClient(iGIMIPtr, si->minorType);
        imageClient->SetDefaultTarget(si->targetID);
        
        if (imageClient->Open() == MaCI::KMaCIOK) {
          ImageLogger *clogger= new ImageLogger(imageClient,name);
          clogger->SetService(*si);
          
          const int numberOfItems = m_listCtrl_Services->GetItemCount();
          const int index = m_listCtrl_Services->InsertItem(numberOfItems, name);
          

          m_listCtrl_Services->SetItemPtrData(index,(wxUIntPtr)(static_cast<Logger *>(clogger)));        
          
          wxColour red(255,0,0);
          m_listCtrl_Services->SetItemTextColour(index,red);
          
        } else {
          std::string s = "Could not open Image client";
          dPrint(1,"%s",s.c_str());

          delete imageClient;
        } 
        ///////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////
      }else{
        dPrint(6,"no can do.. can't recognize major %d",si->majorType);
      }
      ///***************************************************************
      ///***************************************************************
      ///***************************************************************
      ///***************************************************************
      ///***************************************************************
      ///***************************************************************
      //Update window
    }
}
dPrint(3,"Finished to update servicelist ");
  //  m_listCtrl_Services->RefreshItems(0,m_listCtrl_Services->GetItemCount());
  
}
*/
//*****************************************************************************

void MaCI_Logger_MainFrame::OnQuitClick( wxCommandEvent& event )
{
  this->Destroy();
}
//*****************************************************************************

void MaCI_Logger_MainFrame::OnAboutSelected( wxCommandEvent& event )
{

  MaCI_Logger_About_Dialog dia(this,
                               iVersionNumber);
  dia.ShowModal();


}
//*****************************************************************************
void MaCI_Logger_MainFrame::OnAdditionalInfoUpdate( wxTimerEvent &event){
  std::string info;
  
  for(int i = 0; i <m_listCtrl_Services->GetItemCount();i++){
    Logger *log = reinterpret_cast<Logger *>(m_listCtrl_Services->GetItemData(i));

    if(log->GetAdditionalInformation(info)){
      m_listCtrl_Services->SetItem(i,1,wxString(info.c_str(), wxConvUTF8));
    }else{
      wxString s = "-";
      m_listCtrl_Services->SetItem(i,1,s);
    }
  }    

}
//*****************************************************************************

void MaCI_Logger_MainFrame::OnEveryNthSelected( wxCommandEvent& event ){
  
  std::string question = "How many measurement you want to skip? (Only positive values are accepted)";
  int state;
  
  for(unsigned int i = 0; i <m_listCtrl_Services->GetItemCount();i++){
    if(m_listCtrl_Services->GetItemState(i,wxLIST_STATE_SELECTED)){
      Logger *log = reinterpret_cast<Logger *>(m_listCtrl_Services->GetItemData(i));
      if(log->SupportMeasurementSkipping()){
        state = m_listCtrl_Services->GetItemState(i,wxLIST_STATE_SELECTED);
        
        if(state != 0){
          MaCI_Logger_Question_Dialog dia(this,
                                          log,
                                          std::string(m_listCtrl_Services->GetItemText(i).mb_str()),
                                        question);
          dia.ShowModal();
        }
      }else{
        
        std::string er = "'"+log->GetName() + "' doesn't support this feature :(";
        MaCI_Logger_Error_Dialog err(this,er);
        err.ShowModal();
      }
    }

  }



}
//*****************************************************************************

void MaCI_Logger_MainFrame::UpdateLoggerMenus()
{
  for(int item =0 ;item < m_listCtrl_Services->GetItemCount();item++){
    m_menubar1->EnableTop(1,true);
    
    
    Logger *logger = reinterpret_cast<Logger *>(m_listCtrl_Services->GetItemData(item));
    if(logger){
      
      wxMenu *menu = iMenuMap[logger];
      
      if(menu){
        wxMenuItemList itemList = menu->GetMenuItems();
        for(size_t i = 0; i< itemList.GetCount();i++){
          std::string name = std::string(itemList[i]->GetItemLabel().c_str());
          logger->SetMenuItem(name, itemList[i]->IsChecked());

        }

      }


    }

  }


}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
/////////////////////////MaCI Filename Dialog//////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////


MaCI_Logger_Filename_Dialog::MaCI_Logger_Filename_Dialog(wxWindow* parent,
                                                         Logger *aLogger,
                                                         std::string aNameOfService)
  :Filename_Dialog(parent,0,aNameOfService),
   iLogger(aLogger)
{


}
MaCI_Logger_Filename_Dialog::~MaCI_Logger_Filename_Dialog()
{

}

void MaCI_Logger_Filename_Dialog::OnButtonOK( wxCommandEvent& event )
{
  wxString fileName = m_textCtrl_Filename->GetLineText(0);
  iLogger->SetFilename(std::string(fileName.mb_str()));
  Destroy();
}
void MaCI_Logger_Filename_Dialog::OnButtonCancel( wxCommandEvent& event )
{
  Destroy();

}

void MaCI_Logger_Filename_Dialog::OnButtonDefaultName( wxCommandEvent& event )
{
 
  iLogger->SetDefaultFilename();
  Destroy();
 
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
/////////////////////////MaCI Question Dialog//////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
MaCI_Logger_Question_Dialog::MaCI_Logger_Question_Dialog(wxWindow *aParent,
                                                         Logger *aLogger,
                                                         std::string aNameOfService,
                                                         std::string aQuestion)
  :Question_Dialog(aParent,0,aNameOfService),
   iLogger(aLogger)
{
  m_staticText_Question->SetLabel(wxString(aQuestion));

}

MaCI_Logger_Question_Dialog::~MaCI_Logger_Question_Dialog()
{
 
}

void MaCI_Logger_Question_Dialog::OnOk( wxCommandEvent& event )
{
  wxString s = m_textCtrl->GetValue();
  long int numberToSkip = 0;
  if(s.IsNumber()){
    s.ToLong(&numberToSkip);
    if(numberToSkip >= 0){
      if(!iLogger->SkipNMeasurements((unsigned int)numberToSkip)){

        std::string er = "'"+iLogger->GetName() + "' doesn't support this feature :(";
        MaCI_Logger_Error_Dialog err(this,er);
        err.ShowModal();
        Destroy();
      }else{
        dPrint(5,"Succesfully set skipNMeasurements('%u') to logger", (unsigned int)numberToSkip);
        Destroy();
      }
    }else{
      std::string er = "Invalid value. Must be a positive number";
      MaCI_Logger_Error_Dialog err(this,er);
      err.ShowModal();
      Destroy();
    

    }
  }else{
    std::string er = "Invalid value. Must be a positive number";
    MaCI_Logger_Error_Dialog err(this,er);
    err.ShowModal();
    Destroy();
    
  }

}

void MaCI_Logger_Question_Dialog::OnCancel( wxCommandEvent& event )
{
  Destroy();


}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
/////////////////////////MaCI Error Dialog/////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
MaCI_Logger_Error_Dialog::MaCI_Logger_Error_Dialog(wxWindow *aParent,
                                                   std::string aErrorText):
  Error_Dialog(aParent,0)
{
  m_staticText_Error->SetLabel(wxString(aErrorText));

}

MaCI_Logger_Error_Dialog::~MaCI_Logger_Error_Dialog()
{


}

void MaCI_Logger_Error_Dialog::OnOk( wxCommandEvent& event )
{
  Destroy();

}
